package com.book.controller;

import com.book.entity.Account;
import com.book.entity.BookCart;
import com.book.service.CartService;
import com.book.util.ResultBack;
import com.book.vo.CartVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @program:
 * @ClassName:
 * @description:
 * @author: zgc
 * @date:
 * @Version 1.0
 **/
@Controller
@RequestMapping("/cart")
@Slf4j
public class CartController {
    @Resource
    private CartService cartService;
    
    //购物车添加
    @RequestMapping("/addToCart")
    @ResponseBody
    public ResultBack addToCart(BookCart bookCart, HttpSession httpSession) throws Exception {
        Account account = (Account) httpSession.getAttribute("account");
        log.info("Account: " + account);
        Long userid  = account.getId();
        bookCart.setUserId(userid.intValue());
        
        int i = cartService.addToCart(bookCart);
        if (i > 0) {
            return ResultBack.success("添加成功",i);
        }else {
            return ResultBack.failure("添加失败");
        }
    }
    
    //显示购物车
    @RequestMapping("/showCart")
    public String showCart(HttpSession httpSession, Model model) throws Exception  {
        Account account = (Account) httpSession.getAttribute("account");
        
        Long userid = account.getId();
        List<CartVo> list = cartService.findCartByUserId(userid.intValue());

        model.addAttribute("cartList",list);

        return "cart";
    }

    @RequestMapping("/showCartCount")
    @ResponseBody
    public ResultBack showCartCount(HttpSession httpSession) throws Exception {
        Account account = (Account) httpSession.getAttribute("account");
        Long userid = account.getId();
        int count = cartService.findCartCountByUserId(userid.intValue());
        return ResultBack.success("查询成功",count);
    }
    
    
}
